import { IBLEUtilImpl } from ".";

export class WebBLEUtil implements IBLEUtilImpl {

    serviceId: string[];
    device!: BluetoothDevice;
    gatt!: BluetoothRemoteGATTServer;

    constructor(serviceId: string[]) {
        this.serviceId = serviceId;
    }

    /**设置监听 */
    async addEventListener(serviceId: string, uuid: string[], callBack: (values: { uuid: string, values: number[], rawData: any }) => void) {
        let server = await this.gatt.getPrimaryService(serviceId);
        /// 获取蓝牙服务
        var chars = (await server.getCharacteristics());
        chars.forEach(char => {
            if (uuid.includes(char.uuid)) {
                char.startNotifications();
                char.addEventListener("characteristicvaluechanged", (val: any) => {
                    let value = (val.target as any).value as DataView;
                    const length = value.byteLength - (value.byteLength % 2);
                    callBack({
                        uuid: char.uuid,
                        values: [...Array(length).keys()].map(p => value.getUint16(p, true)),
                        rawData: value
                    })
                })
            }
        })
    }

    /**链接蓝牙 */
    async connect() {
        // 先判断是否已经连接过 如过链接过就先断开链接
        await this.close();
        this.device = await navigator.bluetooth.requestDevice({
            optionalServices: this.serviceId,
            acceptAllDevices: true
        });
        try {
            this.gatt = await this.device.gatt?.connect()!;
            return true;
        } catch (error) {
            console.error(error);
            return false;
        }
    }



    /**关闭连接 */
    async close() {
        if (this.gatt?.connected) {
            try {
                return this.gatt.disconnect();
            } catch (error) {

            }
        }
    }


}
